<?php
namespace App\Http\Controllers\ConsoleWeb;

use App\Http\Controllers\Business\Admin\User\UserMamagement;
use App\Http\Controllers\Business\Shop\V1\Salesman\SalesmanManagement;
use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\Admin\Salesman\ShopSalesmanManagement;
use App\Http\Controllers\Business\Admin\Salesman\UserSalesmanManagement;
use App\Http\Controllers\Business\Admin\Shop\ShopManagement;
use App\Http\Controllers\Business\Admin\Shop\QrcodeManagement;
use App\Http\Controllers\Business\Shop\V1\Admin\Admin;
use App\Models\SalesmanHistory;
use App\Models\ShopSalesman;
use App\Http\Controllers\Business\Admin\Auth\AdminAuth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class SalesmanController extends WebController
{
    //地推商家列表
    public function shopLists() {
        $cityId = $this->request->get('cityid');
        $result = ShopSalesmanManagement::shopSalesmanList($cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $adminUserId = Auth::guard('adminweb')->id();
        $editAuth = "shopSalesmanManagement:edit";
        $editAuthResult = AdminAuth::isHasThisAuthByAdminUserId($adminUserId, $editAuth);
        if($editAuthResult) {
            $editPermission = 1;
        } else {
            $editPermission = 0;
        }
        $addAuth = "shopSalesmanManagement:add";
        $addAuthResult = AdminAuth::isHasThisAuthByAdminUserId($adminUserId, $addAuth);
        if($addAuthResult) {
            $addPermission = 1;
        } else {
            $addPermission = 0;
        }
        $data = [
            'cityid' => $cityId,
            'lists' => $lists,
            'editpermission' => $editPermission,
            'addpermission' => $addPermission
            ];
        return view('console.salesman.shop_lists', $data);
    }
    //通过商家代码获取商家信息
    public function searchShop() {
        $cityId = $this->request->get('cityid');
        $shopCode = $this->request->get('shopcode');
        $result = ShopSalesmanManagement::searchShopByCode($cityId, $shopCode);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        return $this->responseSuccessData($data);
    }
    //新增商家
    public function addShopSalesman() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $type = $this->request->get('type');
        $payFee = $this->request->get('payfee');
        $contractMonth = $this->request->get('contractmonth');
        $upgradePassword = $this->request->get('newaddpassword');
        $result = ShopSalesmanManagement::addShopSalesman($shopId, $cityId, $type, $payFee, $contractMonth,$upgradePassword);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        return $this->responseSuccessMessage($result['message']);
    }
    //地推详情
    public function shopGet() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $result = ShopSalesmanManagement::getShopSalesmanDetail($shopId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $data['shopid'] = $shopId;
        return view('console.salesman.shop_get', $data);
    }
    //修改商家地推状态
    public function updateShopSalesmanStatus() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $status = $this->request->get('status');
        $type = $this->request->get('type');
        $payFee = $this->request->get('payfee');
        $contractMonth = $this->request->get('contractmonth');
        $result = ShopSalesmanManagement::updateShopSalesmanStatus($shopId, $status, $payFee, $type, $contractMonth);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //升级商家地推
    public function upgradeShopSalesman() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $payFee = $this->request->get('payfee');
        $upgradePassword = $this->request->get('upgradepassword');
        $contractMonth = $this->request->get('contractmonth');
        $result = ShopSalesmanManagement::upgradeShopSalesman($shopId, $payFee, $contractMonth,$upgradePassword);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //有效订单明细
    public function shopOrderLists() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $date = $this->request->get('date');
        $perpage = 2000; //TODO 分页后续来做
        $result = ShopSalesmanManagement::getShopSalesmanValidOrderDetail($shopId, $date, $perpage);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $data['shopid'] = $shopId;
        $data['date'] = $date;
        return view('console.salesman.shop_order_lists', $data);
    }
    //导出有效订单明细
    public function exportShopOrderLists() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $date = $this->request->get('date');
        $result = ShopSalesmanManagement::exportShopSalesmanValidOrderDetail($shopId, $date);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        $cellData = [
            ['订单时间','订单号','注册用户','消费门店','商家代码', '地推订单实付']
        ];
        foreach($data as $list) {
            $newList = [
                'ordertime' => $list['ordertime'],
                'ordernumber' => $list['ordernumber'],
                'mobile' => $list['mobile'],
                'shopname' => $list['shopname'],
                'shopcode' => $list['shopcode'],
                'orderamount' => $list['orderamount']
            ];
            array_push($cellData, $newList);
        }
        $title = '地推订单明细';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('地推订单明细', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //注册用户明细
    public function shopRegisterLists() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $date = $this->request->get('date');
        $perpage = 2000; //TODO 分页后续来做
        $result = ShopSalesmanManagement::getShopSalesmanRegisterDetail($shopId, $date, $perpage);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $data['shopid'] = $shopId;
        $data['date'] = $date;
        return view('console.salesman.shop_register_lists', $data);
    }
    //导出注册用户明细
    public function exportShopRegisterLists() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $date = $this->request->get('date');
        $result = ShopSalesmanManagement::exportShopSalesmanRegister($shopId, $date);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        $cellData = [
            ['注册时间','注册用户','地推来源','地推来源手机','订单数','地推订单数', '地推订单实付']
        ];
        foreach($data as $list) {
            $newList = [
                'created_at' => $list['created_at'],
                'mobile' => $list['mobile'],
                'registersource' => $list['registersource'],
                'shopusermobile' => $list['shopusermobile'],
                'ordernum' => $list['ordernum'],
                'validordernum' => $list['validordernum'],
                'orderamount' => $list['orderamount']
            ];
            array_push($cellData, $newList);
        }
        $title = '注册用户明细';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('注册用户明细', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //结算详情
    public function shopWithdrawalLists() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $result = ShopSalesmanManagement::getShopSalesmanWithdrawalDetail($shopId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $data['shopid'] = $shopId;
        return view('console.salesman.shop_withdrawal_lists', $data);
    }
    //地推设置
    public function salesmanSetup() {
        $cityId = $this->request->get('cityid');
        $data = [];
        //个人地推列表
        $userSalesmanSetResult = UserSalesmanManagement::userSalesmanSetList($cityId);
        if($userSalesmanSetResult['status'] == 'success') {
            $data['usersalesmanlist'] = $userSalesmanSetResult['data'];
        } else {
            $data['usersalesmanlist'] = [];
        }
        $shopCommonSalesmanSetResult = UserSalesmanManagement::getShopLastSalesmanSet($cityId, 'common');
        if($shopCommonSalesmanSetResult['status'] == 'success') {
            $data['shopcommonsalesman'] = $shopCommonSalesmanSetResult['data'];
        } else {
            $data['shopcommonsalesman'] = [];
        }
        $shopPartnerSalesmanSetResult = UserSalesmanManagement::getShopLastSalesmanSet($cityId, 'partner');
        if($shopPartnerSalesmanSetResult['status'] == 'success') {
            $data['shoppartnersalesman'] = $shopPartnerSalesmanSetResult['data'];
        } else {
            $data['shoppartnersalesman'] = [];
        }
        $data['cityid'] = $cityId;
        return view('console.salesman.salesman_setup', $data);
    }
    //修改地推设置
    public function updateSalesmanSet() {
        $cityId = $this->request->get('cityid');
        $input = $this->request->input();
        if(isset($input['salesmansetid']) && ($input['salesmansetid'] != '')) {
            //编辑
            $result = UserSalesmanManagement::updateSalesmanSet($input);
        } else {
            $result = UserSalesmanManagement::addSalesmanSet($input);
        }
        if($result['status'] == 'success') {
            return $this->responseSuccessMessage($result['message']);
        } else {
            return $this->responseError($result['message']);
        }
    }
    //新增个人地推方案, 或者编辑个人地推
    public function userSalesmanNew() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('salesmansetid')) {
            //编辑
            $salesmanSetId = $this->request->get('salesmansetid');
            $editType = 'edit';
        } else {
            //新增
            $salesmanSetId = '';
            $editType = 'add';
        }
        if($editType == 'edit') {
            $result = UserSalesmanManagement::getSalesmanSetBySalesmanSetId($cityId, $salesmanSetId);
            if($result['status'] == 'failed') {
                return view('errors.404');
            }
            $data = $result['data'];
            $data['edittype'] = $editType;
            $data['cityid'] = $cityId;
            $data['salesmansetid'] = $salesmanSetId;
            return view('console.salesman.salesman_new', $data);
        } else {
            $data = [
                'cityid' => $cityId,
                'edittype' => $editType,
                'salesmansetid' => $salesmanSetId,
            ];
            return view('console.salesman.salesman_new', $data);
        }
    }
    //个人地推方案详情
    public function salesmanDetails() {
        $cityId = $this->request->get('cityid');
        $salesmanSetId = $this->request->get('salesmansetid');
        $basicInfoResult = UserSalesmanManagement::getSalesmanSetBySalesmanSetId($cityId, $salesmanSetId);
        if($basicInfoResult['status'] == 'failed') {
            return view('errors.404');
        }
        $basicInfo = $basicInfoResult['data'];
        $userSalesmanListResult = UserSalesmanManagement::getUserSalesmanListByCityIdAndSalesmanSetId($cityId, $salesmanSetId);
        if($userSalesmanListResult['status'] == 'success') {
            $userSalesmanList = $userSalesmanListResult['data'];
        } else {
            $userSalesmanList = [];
        }
        $data = [
            'salesmansetid' => $salesmanSetId,
            'basicinfo' => $basicInfo,
            'usersalesmanlist' => $userSalesmanList,
            'cityid' => $cityId
        ];
        return view('console.salesman.salesman_details', $data);
    }
    //历史设置记录
    public function salesmanSetupHistoric() {
        $cityId = $this->request->get('cityid');
        $result = UserSalesmanManagement::historySalesmanSetList($cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists'=>$lists,
            'cityid'=>$cityId
        ];
        return view('console.salesman.salesman_setup_historic', $data);
    }
    //个人地推
    public function userSalesmanList() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('search')) {
            $search = $this->request->get('search');
        } else {
            $search = '';
        }
        $result = UserSalesmanManagement::userSalesmanList($cityId, $search);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $userSalesmanSetListResult = UserSalesmanManagement::getUserSalesmanSetIdsAndNames($cityId);
        if($userSalesmanSetListResult['status'] == 'failed') {
            $data['usersalesmansetlist'] = [];
        } else {
            $data['usersalesmansetlist'] = $userSalesmanSetListResult['data'];
        }
        return view('console.salesman.user_salesman_list', $data);
    }
    //新增个人地推人员
    public function addUserSalesman() {
        $cityId = $this->request->get('cityid');
        $userName = $this->request->get('username');
        $mobile = $this->request->get('mobile');
        $salesmanSetId = $this->request->get('salesmansetid');
        $remark = $this->request->get('remark');
        $result = UserSalesmanManagement::addUserSalesman($userName, $mobile, $cityId, $salesmanSetId,$remark);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //个人地推详情
    public function userSalesmanDetails() {
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $result = UserSalesmanManagement::getUserSalesmanDetail($salesmanId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $salesmanSetListResult = UserSalesmanManagement::getUserSalesmanSetIdsAndNames($cityId);
        if($salesmanSetListResult['status'] == 'success') {
            $data['salesmansetlist'] = $salesmanSetListResult['data'];
        } else {
            $data['salesmansetlist'] = [];
        }
        return view('console.salesman.user_salesman_details', $data);
    }
    //修改单个人地推设置
    public function updateSingleUserSalesmanSet() {
        $salesmanSetId = $this->request->get('salesmansetid');
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $result = UserSalesmanManagement::updateSingleUserSalesmanSet($salesmanId, $salesmanSetId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //地推效果方案
    public function userSalesmanResult() {
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $selectSalesmanSetId = $this->request->get('salesmansetid');
        $result = UserSalesmanManagement::getUserSalesmanDetail($salesmanId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        $data['selectsalesmansetid'] = $selectSalesmanSetId;
        return view('console.salesman.user_salesman_result', $data);
    }
    //通过地推id获取地推注册，订单列表
    public function getUseSalesmanRegisterOrOrder() {
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $salesmanSetId = $this->request->get('salesmansetid');
        $type = $this->request->get('type'); //order,register, recharge
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        if($this->request->has('length')) {
            $length = $this->request->get('length');
        } else {
            $length = 20;
        }
        $result = UserSalesmanManagement::getUserSalesmanDetailByType($salesmanId, $salesmanSetId, $type, $page, $length);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessData($result['data']);
        }
    }
    //修改个人地推状态
    public function updateUserSalesmanStatus() {
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $status = $this->request->get('status');
        $result = UserSalesmanManagement::updateUserSalesmanStatus($salesmanId, $status);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //某个人的地推订单
    public function personSalesmanOrderListsByType() {
        $cityId = $this->request->get('cityid');
        $userId = $this->request->get('userid');
        $type = $this->request->get('type');
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        if($this->request->has('length')) {
            $length = $this->request->get('length');
        } else {
            $length = 10;
        }
        if($type == 'usersalesman') {
            //个人地推
            $result = UserSalesmanManagement::personSalesmanOrderLists($userId, $page, $length);
        } else {
            //商家地推
            $result = ShopSalesmanManagement::personSalesmanOrderLists($userId, $page, $length);
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessData($result['data']);
        }
    }
    //批量生成个人地推二维码
    public function batchGenerateUserSalesmanQrCode() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('count')) {
            $count = $this->request->get('count');
        } else {
            $count = 50;
        }
        $result = QrcodeManagement::batchUserQrcode($cityId, $count);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $fileName = $result['data'];
        return response()->download($fileName)->deleteFileAfterSend(true);
    }
    //绑定个人地推二维码
    public function bindingUserSalesmanQrCode() {
        $cityId = $this->request->get('cityid');
        $salesmanId = $this->request->get('salesmanid');
        $qrCode = $this->request->get('qrcode');
        $result = QrcodeManagement::bindingUserQrcode($cityId, $salesmanId, $qrCode);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
}